package bbs.activity;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.xkh.xkh.R;

import java.util.ArrayList;
import java.util.List;

import bbs.adapter.SubmitsAdapter;
import bbs.fragment.SubjectsFragment;
import bbs.fragment.WithMeFragment;
import bbs.model.Submit;
import bbs.model.User;
import bbs.net.GetMoreTieZi;
import bbs.net.MyPost;
import managers.UIHandler;

/**
 * BBS主界面
 * Created by nimi on 2015/11/12.
 */
public class BbsMainActivity extends UIHandler.BaseActivity implements View.OnClickListener, SubjectsFragment.OneSubjectClickListener, WithMeFragment.OnePostClickListener, MyPost.Delegate, GetMoreTieZi.Delegate {
    private static User user = new User();//用户基本信息
    private Button back_bbs;
    private FrameLayout id_bottom_mine;//withme
    private FrameLayout id_bottom_all;//所有主题
    private ListView listView;
    private RelativeLayout relativeLayout;
    //private FrameLayout id_content;
    private SubjectsFragment subjectsFragment;
    private WithMeFragment withMeFragment;
    private MyPost myPost;
    private List<Submit> submits = new ArrayList<Submit>();
    SubmitsAdapter submitAdapter = new SubmitsAdapter(this, submits);
    private static final int MORETIEZI_GET = 0X112;//检测点击上拉
    private Handler mHandler;
    String lasttime;
    int tag = 0;
    boolean isLastRow = false;
    int lastItem;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.bbs_main);

        inituser();
        //id_content=(FrameLayout)findViewById(R.id.id_content);
        back_bbs = (Button) findViewById(R.id.back_bbs);
        back_bbs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent = new Intent(BbsMainActivity.this, FunctionActivity.class);
//                startActivity(intent);
                finish();
            }
        });
        id_bottom_mine = (FrameLayout) findViewById(R.id.id_bottom_mine);
        id_bottom_mine.setOnClickListener(this);
        id_bottom_all = (FrameLayout) findViewById(R.id.id_bottom_all);
        id_bottom_all.setOnClickListener(this);

        setDefaultFragment();//设置默认的fragment
        mHandler = new Handler() {
            public void handleMessage(Message msg)

            {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MORETIEZI_GET:
                        lasttime = submitAdapter.getItem(submits.size() - 1).getBoard_ChangeTime();
                        System.out.print(lasttime);
                        GetMoreTieZi getMoreTieZi;
                        GetMoreTieZi.Upload upload = new GetMoreTieZi.Upload();
                        upload.setLastTime(lasttime);
                        // TODO
//                        upload.setUserId(UserInfo.userID);
                        getMoreTieZi = new GetMoreTieZi(upload);
                        getMoreTieZi.setDelegate(BbsMainActivity.this);
                        getMoreTieZi.get();
                        break;

                }

            }
        };
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        tag = 0;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        tag = 0;
    }

    /*初始化用户*/
    private void inituser() {
        MyPost.Upload upload = new MyPost.Upload();
        // TODO
//        upload.setUserId(UserInfo.userID);
//        upload.setUserName(UserInfo.getUserName());
        myPost = new MyPost(upload);
        myPost.setDelegate(BbsMainActivity.this);
        myPost.get();


    }

    private void setDefaultFragment() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        withMeFragment = new WithMeFragment();
        transaction.replace(R.id.id_content, withMeFragment);
        transaction.commit();
    }

    public void onClick(View v) {
        FragmentManager fm = getFragmentManager();
        // 开启Fragment事务
        FragmentTransaction transaction = fm.beginTransaction();
        switch (v.getId()) {
            case R.id.id_bottom_all:
                if (subjectsFragment == null) {
                    subjectsFragment = new SubjectsFragment();
                }
                // 使用当前Fragment的布局替代id_content的控件
                transaction.replace(R.id.id_content, subjectsFragment);
                break;
            case R.id.id_bottom_mine:
                //inituser();
                if (withMeFragment == null) {
                    withMeFragment = new WithMeFragment();
                }
                transaction.replace(R.id.id_content, withMeFragment);
                break;
        }
        transaction.commit();
    }

    public void oneSubjectClickListener() {//主题被点击

       /* Intent intent = new Intent(BbsMainActivity.this, OneSubjectActivity.class);
        startActivity(intent);*/

    }

    public void onePostClickListener() {//贴子被点击

    }

    public void onResponse(String response, MyPost myPost) {
        if (myPost.getDownload().getStatus() == 1) {
            submits.addAll(myPost.getDownload().getTies());
            submitAdapter.notifyDataSetChanged();
            listView = (ListView) findViewById(R.id.subjectlist);
            LayoutInflater inflater = BbsMainActivity.this.getLayoutInflater();
            relativeLayout = (RelativeLayout) inflater.inflate(R.layout.bbs_footer_listview, null);
            if (submits.size() >= 10)
                listView.addFooterView(relativeLayout, null, false);
            listView.setAdapter(submitAdapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    System.out.print(submits.size());
                    Submit submit = submits.get(i);
                    Intent intent = new Intent(BbsMainActivity.this, OnePostActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("submitID", submit.getBoard_ID());
                    bundle.putString("subjectID", submit.getTopic_ID());
//                    bundle.putString("subjectName", );
                    bundle.putString("submitName", submit.getBoard_Title());
                    bundle.putString("submitContent", submit.getBoard_Content());
                    bundle.putString("submitTime", submit.getBoard_IssueTime());
                    bundle.putString("userName", submit.getUser_RealName());
                    intent.putExtras(bundle);
                    startActivity(intent);

                }
            });


            listView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView absListView, int scoll) {
                    switch (scoll) {
                        case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                            break;
                        case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                            break;
                        case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                            if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1)) {
                                System.out.println(absListView.getLastVisiblePosition() + ".....");
                                Message message = new Message();
                                message.what = MORETIEZI_GET;
                                mHandler.sendMessage(message);
                                isLastRow = false;
                            }
                            break;
                        default:
                            break;
                    }

                }

                @Override
                public void onScroll(AbsListView absListView, int i, int i1, int i2) {

                    if (i + i1 == i2 && i2 > 0 && tag == 0)
                        isLastRow = true;
                }
            });
        }
    }

    public void onErrorResponse(VolleyError error, MyPost myPost) {

    }

    public void onResponse(String response, GetMoreTieZi getMoreTieZi) {
        if (getMoreTieZi.getDownload().getTies().size() > 0) {
            Toast.makeText(this, "加载成功", Toast.LENGTH_SHORT).show();
            int num = submits.size();
            submits.addAll(num, getMoreTieZi.getDownload().getTies());
            submitAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(this, "没有更多数据", Toast.LENGTH_SHORT).show();
            tag = 1;
            listView.removeFooterView(relativeLayout);
        }

    }

    public void onErrorResponse(VolleyError error, GetMoreTieZi getMoreTieZi) {

    }


}
